package cn.xuexiluxian.open.admin.controller.system;

import cn.hutool.core.util.StrUtil;
import cn.xuexiluxian.open.common.annotation.Log;
import cn.xuexiluxian.open.common.annotation.RepeatSubmit;
import cn.xuexiluxian.open.common.enums.BusinessType;
import cn.xuexiluxian.open.system.model.entity.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cn.xuexiluxian.open.common.enums.ResultStatusCodeEnum;
import cn.xuexiluxian.open.common.response.ResponseResult;
import cn.xuexiluxian.open.system.model.dto.SystemRoleDTO;
import cn.xuexiluxian.open.system.model.req.SystemRoleREQ;
import cn.xuexiluxian.open.system.model.req.SystemUserRoleREQ;
import cn.xuexiluxian.open.system.service.ISystemRoleMenuService;
import cn.xuexiluxian.open.system.service.ISystemRoleService;
import cn.xuexiluxian.open.system.service.ISystemUserRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 角色管理
 */
@Slf4j
@RestController
@RequestMapping("system/role")
public class SystemRoleController {
    @Autowired
    private ISystemRoleService systemRoleService;
    @Autowired
    private ISystemRoleMenuService systemRoleMenuService;
    @Autowired
    private ISystemUserRoleService systemUserRoleService;
    /**
     * 分页查询角色
     * @param page
     * @param params
     * @return
     */
    @GetMapping(value = "page")
    @Log(title = "角色管理", businessType = BusinessType.SELECT)
    @PreAuthorize("@permission.hasPermission('system:role:page')")
    public ResponseResult page(Page page, SystemRoleREQ params) {
        Page<SystemRole> pageList = systemRoleService.pageList(page, params);
        return ResponseResult.ok(pageList);
    }

    /**
     * 删除角色
     * @param id
     * @return
     */
    @RepeatSubmit
    @GetMapping("delete/{id}")
    @Log(title = "角色管理", businessType = BusinessType.DELETE)
    @PreAuthorize("@permission.hasPermission('system:role:delete')")
    public ResponseResult delete(@PathVariable String id){
        if(StrUtil.isBlank(id)){
            return ResponseResult.error(ResultStatusCodeEnum.PARAM_REQUIRE_ERROR);
        }

        QueryWrapper<SystemUserRole> queryWrapper1 = new QueryWrapper<SystemUserRole>();
        queryWrapper1.eq("role_id", id);
        List<SystemUserRole> userRoles = systemUserRoleService.list(queryWrapper1);
        if(userRoles != null && userRoles.size() > 0){
            return ResponseResult.error(ResultStatusCodeEnum.DATA_HAS_RESOURCES);
        }

        QueryWrapper<SystemRoleMenu> queryWrapper = new QueryWrapper<SystemRoleMenu>();
        queryWrapper.eq("role_id", id);
        systemRoleMenuService.remove(queryWrapper);

        boolean b = systemRoleService.removeById(id);
        if(b){
            return ResponseResult.ok();
        }
        return ResponseResult.error(ResultStatusCodeEnum.HTTP_ERROR);
    }

    /**
     * 角色详情
     * @param id
     * @return
     */
    @GetMapping("get/{id}")
    @Log(title = "角色管理", businessType = BusinessType.SELECT)
    @PreAuthorize("@permission.hasPermission('system:role:get')")
    public ResponseResult get(@PathVariable String id){
        if(StrUtil.isBlank(id)){
            return ResponseResult.error(ResultStatusCodeEnum.PARAM_REQUIRE_ERROR);
        }
        SystemRole systemRole = systemRoleService.getById(id);
        if(systemRole != null){
            List<String> permissionIds = systemRoleMenuService.selectCheckedByRoleId(id);
            Map<String, Object> result = new HashMap<>();
            result.put("role", systemRole);
            result.put("permissions", permissionIds);
            return ResponseResult.ok(result);
        }
        return ResponseResult.error(ResultStatusCodeEnum.DATA_NO_EXIST);
    }

    /**
     * 添加角色
     * @param systemRoleDTO
     * @return
     */
    @RepeatSubmit
    @PostMapping("add")
    @Log(title = "角色管理", businessType = BusinessType.INSERT)
    @PreAuthorize("@permission.hasPermission('system:role:add')")
    public ResponseResult add(@RequestBody SystemRoleDTO systemRoleDTO){
        boolean b = systemRoleService.saveBean(systemRoleDTO);
        if(b){
            return ResponseResult.ok();
        }
        return ResponseResult.error(ResultStatusCodeEnum.HTTP_ERROR);
    }

    /**
     * 修改角色
     * @param systemRoleDTO
     * @return
     */
    @RepeatSubmit
    @PostMapping("update")
    @Log(title = "角色管理", businessType = BusinessType.UPDATE)
    @PreAuthorize("@permission.hasPermission('system:role:update')")
    public ResponseResult update(@RequestBody SystemRoleDTO systemRoleDTO){
        if(systemRoleDTO == null || StrUtil.isBlank(systemRoleDTO.getId())){
            return ResponseResult.error(ResultStatusCodeEnum.PARAM_REQUIRE_ERROR);
        }
        boolean b = systemRoleService.updateBean(systemRoleDTO);
        if(b){
            return ResponseResult.ok();
        }
        return ResponseResult.error(ResultStatusCodeEnum.HTTP_ERROR);
    }

    /**
     * 全部角色
     * @return
     */
    @GetMapping("all")
    @Log(title = "角色管理", businessType = BusinessType.SELECT)
    @PreAuthorize("@permission.hasPermission('system:role:page')")
    public ResponseResult all(){
        QueryWrapper<SystemRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("enabled", 1);
        queryWrapper.orderByDesc("create_time");
        List<SystemRole> list = systemRoleService.list(queryWrapper);
        return ResponseResult.ok(list);
    }

    /**
     * 已授权用户
     * @param page
     * @param systemUserRoleREQ
     * @return
     */
    @GetMapping("assigned")
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    @PreAuthorize("@permission.hasPermission('system:role:assigned')")
    public ResponseResult assigned(Page page, SystemUserRoleREQ systemUserRoleREQ){
        if(systemUserRoleREQ == null || StrUtil.isBlank(systemUserRoleREQ.getRoleId())){
            return ResponseResult.error(ResultStatusCodeEnum.PARAM_REQUIRE_ERROR);
        }
        Page<SystemUser> pageList = systemUserRoleService.selectListByRoleId(page, systemUserRoleREQ);
        return ResponseResult.ok(pageList);
    }

    /**
     * 取消用户授权
     * @param systemUserRoles
     * @return
     */
    @RepeatSubmit
    @PostMapping("cancel")
    @Log(title = "角色管理", businessType = BusinessType.GRANT)
    @PreAuthorize("@permission.hasPermission('system:role:grant')")
    public ResponseResult cancel(@RequestBody List<SystemUserRole> systemUserRoles){
        if(systemUserRoles == null || systemUserRoles.size() <= 0){
            return ResponseResult.error(ResultStatusCodeEnum.PARAM_REQUIRE_ERROR);
        }
        boolean b = systemUserRoleService.cancel(systemUserRoles);
        if(b){
            return ResponseResult.ok();
        }
        return ResponseResult.error(ResultStatusCodeEnum.HTTP_ERROR);
    }
}
